package cn.tedu.sp06.filter;

import cn.tedu.sp01.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class AccessFilter extends ZuulFilter {
    //过滤器类型:pre, routing, post, error
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    //过滤器添加的顺序号
    @Override
    public int filterOrder() {
        return 6;
    }
    //针对当前请求判断是否执行过滤代码
    //请求商品要检查权限,请求用户和订单不检查权限
    @Override
    public boolean shouldFilter() {
        //判断当前调用的后台服务,是不是item-service

        //获得 调用服务id
        RequestContext context = RequestContext.getCurrentContext();
        String serviceId = (String) context.get(FilterConstants.SERVICE_ID_KEY);
        //如果id是item-service,返回true
        return "item-service".equals(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //接收token参数
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");
        //如果没有token
        if (StringUtils.isBlank(token)){
             //阻止继续调用
            currentContext.setSendZuulResponse(false);
            //直接返回响应
            String json = JsonResult.err().code(JsonResult.NOT_LOGIN).msg("Not Login! 未登录!").toString();
            currentContext.addZuulRequestHeader("Content-type", "application/json;charset=UTF-8");
            currentContext.setResponseBody(json);
        }
        //zuul当前版本中没有使用这个方法回执,不起任何作用
        return null;
    }
}
